#include "../include/processor/CardProcessor.hpp"
#include "processor/DefaultProcessor.hpp"
#include "processor/CardPickProcessor.h"
#include "processor/CardParamPickProcessor.h"
#include <iostream>
#include <opencv2/core/mat.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
int main() {

  /**
   * WARNING:
   * --------------------------------------------------------------------------------------
   * 1. 继承并实现 include/processor下图像处理模板类
   * 2. 编译可执行文件时,只需替换 DefaultGrayScaleProcessor processor;
   * 3. 不要在此处测试使用, 在test目录下完成功能和单元测试
   */
  // 读取参数
  int startX, startY, width, height;
  std::cin >> startX >> startY >> width >> height;

  // 清理输入缓冲区中的剩余字符（包括换行符）
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  // 从标准输入读取图像数据
  std::vector<unsigned char> buffer;
  unsigned char byte;
  while (std::cin.read(reinterpret_cast<char *>(&byte), 1)) {
    buffer.push_back(byte);
  }

  if (buffer.empty()) {
    std::cerr << "无法读取图像数据，请确保输入数据正确" << std::endl;
    return -1;
  }

  // 将字节数据解码为 OpenCV Mat 对象
  cv::Mat image = cv::imdecode(buffer, cv::IMREAD_COLOR);
  if (image.empty()) {
    std::cerr << "无法解码图像数据，请确保数据格式正确" << std::endl;
    return -1;
  }
  // -------------------------------------------------------

  // 调用函数
  // NOTE: 只更改这里即可
  // WARNING: 测试功能请在test包下完成
  CardParamPickProcessor processor;
//  auto [msg, tcResult, grayValues, pc, pt, cValue, tValue, tcRatio] =
//      processor.GetGrayScaleArray(image, startX, startY, width, height);
//

  // 调用函数
  TcResponseInfo tcResponseInfo = processor.GetTcResponseInfo(image, startX, startY, width, height);

  // 输出日志信息
  std::cout << "Debug: Starting JSON output..." << std::endl;

  // 打印灰度区域宽高（日志信息）
  std::cout << "Gray region width: 640, height: 480" << std::endl;

  // 输出 JSON 数据并添加特殊标记
  std::cout << "---JSON-BEGIN---" << std::endl;
  std::cout << "{" << std::endl;
  std::cout << "  \"msg\": \"" << tcResponseInfo.msg << "\"," << std::endl; // 添加双引号
  std::cout << "  \"tcResult\": \"" << tcResponseInfo.tcResult << "\","
            << std::endl; // 添加双引号
  std::cout << "  \"grayValues\": [";
  for (size_t i = 0; i < tcResponseInfo.grayValues.size(); ++i) {
    std::cout << static_cast<int>(tcResponseInfo.grayValues[i]);
    if (i != tcResponseInfo.grayValues.size() - 1) {
      std::cout << ", ";
    }
  }
  std::cout << "]," << std::endl;

  std::cout << "  \"pc\": " << tcResponseInfo.pc << "," << std::endl;
  std::cout << "  \"pt\": " << tcResponseInfo.pt << "," << std::endl;
  std::cout << "  \"cValue\": " << tcResponseInfo.cValue << "," << std::endl;
  std::cout << "  \"tValue\": " << tcResponseInfo.tValue << "," << std::endl;
  std::cout << "  \"tcRatio\": " << tcResponseInfo.tcRatio << std::endl;
  std::cout << "}" << std::endl;
  std::cout << "---JSON-END---" << std::endl;

  // 输出日志信息
  std::cout << "Debug: Finished JSON output." << std::endl;
  return 0;
}
